const int QFkaiPin = 5;    // 定义球阀开关输出引脚
const int QFguanPin = 15;  // 定义球阀开关输出引脚
const int liuShuiPin = 16; // 定义流水状态输入引脚
const int ZYBStatePin = 4; // 定义增压状态输入引脚

bool data_State = false; // 数据状态
bool ZYB_State = false; // 增压状态
bool WiF_State = false; // 流水状态
unsigned long sendtoTick = 0;
unsigned long preHeartTick_A = 0;

void sendtoServer();
void receiveTCPServerA(String TcpClient_Buff);
void receiveUDPServer();
void ZYB_onoff(bool c);
void QF_onoff(bool c);
void QF_An();
void autoZengYa();
void setupSystemA();
void loopSystemA();

void sendtoServer()
{
    // sensors.requestTemperatures();
    // ShuiWenValue = sensors.getTempCByIndex(0);
    sendtoTCPServer("cmd=2&uid=" + UID + "&topic=" + TOPIC2 + "/up&msg=" + (config.QF_State ? "on" : "off") + "\r\n"); // 推送消息
    sendtoTCPServer("cmd=2&uid=" + UID + "&topic=" + TOPIC1 + "/up&msg=" + (ZYB_State ? "on" : "off") + "#" + ShuiWeiValue + "#" + ShuiYaValue + "#" + ShuiWenValue + "#" + config.Auto_State + "#" + config.QF_State + "#" + WiF_State + "\r\n"); // 推送消息
}

void receiveTCPServerA(String TcpClient_Buff)
{
    if (TcpClient_Buff.indexOf("ZYB_on") > 0 || TcpClient_Buff.indexOf("" + TOPIC1 + "&msg=on") > 0)
    {
        Serial.println("ZYB_on");
        config.Auto_State = true;
        ZYB_onoff(true);
    }
    else if (TcpClient_Buff.indexOf("ZYB_off") > 0 || TcpClient_Buff.indexOf("" + TOPIC1 + "&msg=off") > 0)
    {
        Serial.println("ZYB_off");
        config.Auto_State = false;
        ZYB_onoff(false);
    }
    else if (TcpClient_Buff.indexOf("QF_on") > 0 || TcpClient_Buff.indexOf("" + TOPIC2 + "&msg=on") > 0)
    {
        Serial.println("QF_on");
        QF_onoff(true);
    }
    else if (TcpClient_Buff.indexOf("QF_off") > 0 || TcpClient_Buff.indexOf("" + TOPIC2 + "&msg=off") > 0)
    {
        Serial.println("QF_off");
        ZYB_onoff(false);
        QF_onoff(false);
    }
}

void receiveUDPServer()
{
    if (WiFi.status() == WL_CONNECTED)
    {
        // 获取上位机传递过来的数据长度
        int data_len = udp.parsePacket();
        // 如果长度非0，表示数据存在且有效
        if (data_len)
        {
            // 读取长度为255字节的数据并将他们保存到缓冲区buff里面
            int len = udp.read(packetBuffer, 255);
            // 由于长度不可能总是255，对于多出来的乱码部分采用截断处理
            if (len > 0)
            {
                packetBuffer[len] = 0;
                int msgIndex = String(packetBuffer).indexOf("data=");
                if (msgIndex != -1)
                {
                    String msgPart = String(packetBuffer).substring(msgIndex + 5);
                    int firstHashIndex = msgPart.indexOf("#");
                    int secondHashIndex = msgPart.indexOf("#", firstHashIndex + 1);
                    if (firstHashIndex != -1 && secondHashIndex != -1)
                    {
                        String adcValueStr = msgPart.substring(0, firstHashIndex);
                        String pressureStr = msgPart.substring(firstHashIndex + 1, secondHashIndex);
                        String temperatureStr = msgPart.substring(secondHashIndex + 1);
                        ShuiWeiValue = adcValueStr.toFloat();
                        ShuiYaValue = pressureStr.toFloat();
                        ShuiWenValue = temperatureStr.toFloat();
                        Serial.print("水位: ");
                        Serial.println(ShuiWeiValue);
                        Serial.print("压力: ");
                        Serial.println(ShuiYaValue);
                        Serial.print("温度: ");
                        Serial.println(ShuiWenValue);
                        data_State = true;
                    }
                }


                
                if (millis() - sendtoTick >= 1000)
                {
                    sendtoServer();
                    sendtoTick = millis();
                }
            }
        }
    }
}

void ZYB_onoff(bool c)
{
    if (c && !ZYB_State && config.QF_State)
    {
        Serial.println("ZYB_on");
        pinMode(buttonPin, OUTPUT);
        digitalWrite(buttonPin, LOW);
        delay(100);
        pinMode(buttonPin, INPUT);
        ZYB_State = c;
    }
    else if (!c && ZYB_State)
    {
        Serial.println("ZYB_off");
        pinMode(buttonPin, OUTPUT);
        digitalWrite(buttonPin, LOW);
        delay(100);
        pinMode(buttonPin, INPUT);
        ZYB_State = c;
    }
}

void QF_onoff(bool c)
{
    digitalWrite(LedBlink, HIGH); // 切换指示灯状态
    delay(100);
    digitalWrite(LedBlink, LOW); // 切换指示灯状态
    if (c)
    {
        Serial.println("QF_on");
        digitalWrite(QFkaiPin, HIGH);
    }
    else
    {
        Serial.println("QF_off");
        digitalWrite(QFguanPin, HIGH);
    }
    config.QF_State = c;
    delay(5000);
    digitalWrite(QFkaiPin, LOW);
    digitalWrite(QFguanPin, LOW);
}

void QF_An()
{
    static int i = 0;
    if (!digitalRead(buttonPin))
    {
        i++;
        if (i > 3000)
        {
            QF_onoff(!config.QF_State);
        }
    }
    else
    {
        i = 0;
    }
}

void autoZengYa()
{
    static unsigned long ZY_Time = 0;
    static bool Diwen = false;
    static bool Diwen_State = false;
    static bool ZY_State = false;
    static bool QF_State = config.QF_State;
    static bool Auto_State = config.Auto_State;

    WiF_State = !digitalRead(liuShuiPin);
    ZYB_State = digitalRead(ZYBStatePin);
    Diwen = data_State && ShuiWenValue <= 1 && ShuiWenValue >= -10;

    // if (config.QF_State && config.Auto_State)
    // {
    //     if (!ZYB_State && ShuiYaValue < 1.00)
    //     {
    //         ZYB_onoff(true);
    //     }
    //     else if (ZYB_State && ShuiYaValue > 2.00)
    //     {
    //         ZYB_onoff(false);
    //     }
    // }

    if (ZYB_State) // 打开增压后检测流水状态
    {
        if (!WiF_State) // 如果没有水
        {
            if (millis() - ZY_Time >= 10000) // 超时后关闭增压泵
            {
                ZYB_onoff(WiF_State);
            }
        }
        else
        {
            ZY_Time = millis();
        }
    }
    else
    {
        ZY_Time = millis();
    }

    if (ZY_State != ZYB_State) // 发送增压泵的状态
    {
        sendtoServer();
        ZY_State = ZYB_State;
        // doHttpStick(ZYB_State ? "增压已打开" : "增压已关闭");
    }

    if (Auto_State != config.Auto_State) // 发送增压泵的状态
    {
        sendtoServer();
        Auto_State = config.Auto_State;
        saveConfig();
        // doHttpStick(ZYB_State ? "自动已打开" : "自动已关闭");
    }

    if (QF_State != config.QF_State) // 发送球阀的状态
    {
        sendtoServer();
        QF_State = config.QF_State;
        saveConfig();
        // doHttpStick(config.QF_State ? "球阀已打开" : "球阀已关闭");
    }

    if (Diwen != Diwen_State) // 低温保护
    {
        if (Diwen)
        {
            QF_onoff(true);
        }
        else
        {
            QF_onoff(false);
        }
        doHttpStick(Diwen ? "低温保护已打开" : "低温保护已关闭");
        Diwen_State = Diwen;
    }
}

void setupSystemA()
{
    pinMode(QFkaiPin, OUTPUT);
    pinMode(QFguanPin, OUTPUT);
    pinMode(liuShuiPin, INPUT);
    pinMode(ZYBStatePin, INPUT);
    udp.begin(receiverPort);
}

void loopSystemA()
{
    if (millis() - preHeartTick_A >= 100)
    {
        QF_An();
        autoZengYa();
        receiveUDPServer();
        preHeartTick_A = millis();
    }
}
